<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\store\model\ding;

use app\api\model\ding\ClerkMember as ClerkMemberModel;
use app\api\model\ding\OrderLog as OrderLogModel;
use app\api\model\ding\OrderSeat as OrderSeatModel;
use app\api\model\wxapp\Setting as WxappSettingModel;
use app\common\enum\ding\OrderType as OrderTypeEnum;
use app\common\library\wechat\Link;
use app\common\model\ding\Order as OrderModel;
use app\common\service\Day as DayService;
use app\common\service\message\ding\Order as OrderSendService;
use app\common\service\Order as OrderService;
use app\common\service\store\User as UserService;
use app\store\service\wxapp\Message as MessageService;
use think\facade\Db;
use app\common\service\order\Printer as PrinterService;

/**
 * 商品分类模型
 * Class Category
 * @package app\store\model
 */
class Order extends OrderModel {

	/**
     * 小票打印
     * @param array $data
     * @return bool
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function printer(array $data): bool
    {
        // 实例化打印机驱动
        $Printer = new PrinterService;
        // 手动打印小票
        $status = $Printer->printEvent($this, $data['printerId']);
        if ($status === false) {
            $this->error = $Printer->getError();
        }
        return $status;
    }

	private static function getMpWxConfig(): array {
		$wxConfig = WxappSettingModel::getWxappConfig();
		if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
			throwError('请到后台小程序设置填写AppID和AppSecret参数');
		}
		return $wxConfig;
	}
	/**
	 * 订单列表
	 * @param string $dataType 订单类型
	 * @param array $param
	 * @return mixed
	 */
	public function getListUser(string $dataType = 'all', array $param = []) {
		// 检索查询条件
		$filter = $this->getQueryFilter($param);
		// 设置订单类型条件
		$dataTypeFilter = $this->getFilterDataType($dataType);
		// 获取数据列表
		return $this->with(['user.avatar', 'shop'])
			->alias('order')
			->field('order.*')
			->leftJoin('user', 'user.user_id = order.user_id')
			->where($dataTypeFilter)
			->where($filter)
		//	->where('order.user_id', '>', 0)
			->where('order.is_delete', '=', 0)
			->order(['order.create_time' => 'desc'])
			->paginate(10);
	}
	/**
	 * 设置检索查询条件
	 * @param array $param
	 * @return array
	 */
	private function getQueryFilter(array $param): array {
		// 默认参数
		$params = $this->setQueryDefaultValue($param, [
			'searchType' => '', // 关键词类型 (10订单号 20会员昵称 30会员ID 40收货人姓名 50收货人电话)
			'searchValue' => '', // 关键词内容
			'orderSource' => -1, // 订单来源
			'payType' => -1, // 支付方式
			'deliveryType' => -1, // 配送方式
			'betweenTime' => [], // 起止时间
			'userId' => 0, // 会员ID
		]);
		// 检索查询条件
		$filter = [];
		// 关键词
		if (!empty($params['searchValue'])) {
			$searchWhere = [
				10 => ['order.order_no', 'like', "%{$params['searchValue']}%"],
				20 => ['user.nick_name', 'like', "%{$params['searchValue']}%"],
				30 => ['order.user_id', '=', (int) $params['searchValue']],
				40 => ['address.name', 'like', "%{$params['searchValue']}%"],
				50 => ['address.phone', 'like', "%{$params['searchValue']}%"],
			];
			array_key_exists($params['searchType'], $searchWhere) && $filter[] = $searchWhere[$params['searchType']];
		}
	
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['order.create_time', '>=', $times['start_time']];
			$filter[] = ['order.create_time', '<', $times['end_time'] + 86400];
		}
		// 订单来源
		$params['orderSource'] > -1 && $filter[] = ['order_source', '=', (int) $params['orderSource']];
		// 支付方式
		$params['payType'] > -1 && $filter[] = ['pay_type', '=', (int) $params['payType']];
		// 配送方式
		$params['deliveryType'] > -1 && $filter[] = ['delivery_type', '=', (int) $params['deliveryType']];
		// 用户id
		$params['userId'] > 0 && $filter[] = ['order.user_id', '=', (int) $params['userId']];
		return $filter;
	}

	/**
	 * 设置订单类型条件
	 * @param string $dataType
	 * @return array
	 */
	private function getFilterDataType(string $dataType = self::LIST_TYPE_ALL): array {
		// 数据类型
		$filter = [];
		switch ($dataType) {
		case 'all':
			$filter = [];
			break;
		//待确认
		case 'queu':
			$filter[] = ['order_status', '=', 0];
			break;
		//待使用
		case 'use':
			$filter[] = ['order_status', '=', 10];

			break;
		//待付款
		case 'pay':
			$filter[] = ['order_status', '=', 10];
			$filter[] = ['pay_status', '=', 10];
			break;
		//已完成
		case 'complate':
			$filter[] = ['order_status', '=', 40];

			break;
		//已完成
		case 'cancel':
			$filter[] = ['order_status', 'in', [20, 30]];

			break;
		}
		return $filter;
	}
	public function add(array $data) {

		$order = Db::name('ding_order_seat')
			->where('type', $data['type'])
			->where('date', $data['date'])
			->where('seat_id', $data['seat_id'])

			->where('status', '<', 30)->find();

		//判断是否被预订
		if ($order) {
			$this->error = '已被预订';
			return false;
		}

		// 当前用户信息

		$store_user_id = UserService::getLoginInfo()['user']['store_user_id'];

		$shopId = Db::name('store_user')->where('store_user_id', $store_user_id)->value('shop_id');

		$c = new DayService();

		$date_arr = explode('-', $data['date']);

		$data['week'] = $c->get_week_day($data['date']);
		$data['order_no'] = OrderService::createOrderNo();
		$today = $c->convertSolarToLunar($date_arr[0], $date_arr[1], $date_arr[2]);
		$data['lunar_date'] = $today[1] . $today[2];

		$clerk=Db::name('store_shop_clerk')->where('shop_id',$shopId)->where('role_id',3)->find();
		if(!$clerk){
			$this->error = '请先设置老板账号';
			return false;
		}

		$data = array_merge($data, ['clerk_id' =>$clerk['clerk_id'] , 'shop_id' => $shopId,
			'store_id' => self::$storeId]);

		$data['order_status'] = 10;

		$this->save($data);
		if (isset($data['contentList'])) {
			// 内容
			OrderContentModel::increased((int) $this['id'], $data['contentList']);
		}
		if (!empty($data['mobile'])) {
			$clerkMember = new ClerkMemberModel;
			$clerkMember->add($data);
		}
		//餐位
		$data['order_id'] = $this['id'];

		OrderSeatModel::increased($data);

		//操作日记
		$log['content'] = '后台创建了此订单';
		$log['status'] = OrderTypeEnum::CREATE;
		$log['order_id'] = $this['id'];
		$log['clerk_id'] = 0;
		$log['shop_id'] = $shopId;

		OrderLogModel::increased($log);

		$orderId = $this['id'];

		$clerks = Db::name('store_shop_clerk')->where('shop_id', $shopId)
			->group('user_id')
			->where('reserve_msg', 1)
			->select()->toArray();
		$shop = Db::name('store_shop')->where('shop_id', $shopId)->find();
	
		foreach ($clerks as $key => $value) {
		
			$opend_id = $value['oauth_id'];
			if ($opend_id) {
				// 执行发送

				$MessageService = new MessageService;
				$content['template_id'] = 'yWrzJ1FuLCamRw_Rm55kwvtylWYD0JGys1U7g4_fMmk';
				$content['page'] = 'pagesNew/order/detail?orderId=' . $orderId . '&shopId=' . $shopId;

				$content['data']['thing4'] = $shop['shop_name'];
				$content['data']['time3'] = $data['date'] . ' ' . $data['time'];
				$content['data']['character_string5'] = $data['order_no'];
				$content['data']['thing6'] = $data['name'];
				$content['data']['const1'] = '订座成功';
				$content['data']['time4'] = $data['date'] . ' ' . $data['time'];
				//暂时注释
				$MessageService->send($opend_id, $content);

			}
		}

		//发送短信
		if ($data['is_send'] == 1) {
			$messageService = new OrderSendService(self::$storeId);
			$sex = '先生/女士';
			if ($data['sex'] == 1) {
				$sex = '先生';
			} elseif ($data['sex'] == 2) {
				$sex = '女士';
			}
			// 获取当前小程序信息
			$config = self::getMpWxConfig();
			// 微信登录 (获取session_key)
			$WxUser = new Link($config['app_id'], $config['app_secret']);

			$param['path'] = 'pagesNew/order/detail';
			$param['query'] = 'orderId=' . $this['id'] . '&shopId=' . $shopId;

			$result = $WxUser->getLinkLong($param);
			$url = $result['url_link'];

			$date = $data['date'] . ' ' . $data['time'];
			$send['users'] = [['real_name' => $data['real_name'] . $sex, 'mobile' => $data['mobile'], 'date' => $date, 'seat_name' => $data['name'], 'page' => $url]];
			$send['clerk'] = $clerk;
			$send['shop'] = $shop;

			$messageService->send($send);
		}

		return $this['id'];

	}

	public function edit(array $data) {
		// 当前用户信息

		$store_user_id = UserService::getLoginInfo()['user']['store_user_id'];

		$shopId = Db::name('store_user')->where('store_user_id', $store_user_id)->value('shop_id');

		$c = new DayService();

		$date_arr = explode('-', $data['date']);

		$data['week'] = $c->get_week_day($data['date']);
		$data['order_no'] = OrderService::createOrderNo();
		$today = $c->convertSolarToLunar($date_arr[0], $date_arr[1], $date_arr[2]);
		$data['lunar_date'] = $today[1] . $today[2];

		$data = array_merge($data, ['clerk_id' => 0, 'shop_id' => $shopId,
			'store_id' => self::$storeId]);

		$data['order_status'] = 10;

		$this->save($data);
		if (isset($data['contentList'])) {
			// 内容
			OrderContentModel::increased((int) $this['id'], $data['contentList']);
		}
		if (!empty($data['mobile'])) {
			$clerkMember = new ClerkMemberModel;
			$clerkMember->add($data);
		}
		//餐位
		$data['order_id'] = $this['id'];

		OrderSeatModel::increased($data);

		//操作日记
		$log['content'] = '后台编辑了此订单';
		$log['status'] = OrderTypeEnum::CREATE;
		$log['order_id'] = $this['id'];
		$log['clerk_id'] = 0;
		$log['shop_id'] = $shopId;

		OrderLogModel::increased($log);

		return $this['id'];

	}
	/**
	 * 订单详情页数据
	 * @param int $orderId
	 * @return Order|array|false|null
	 */
	public function getDetail(int $orderId) {
		return static::detail($orderId, [
			'user',
			'shop',
			'goods.image',

		]) ?: false;
	}

	/**
	 * 确认
	 * @param $data
	 * @return bool|false
	 * @throws \Exception
	 */
	public function queu($data): bool {
		$this->save(['order_status' => 10]);
		return true;
	}
	/**
	 * 删除记录
	 * @return bool
	 */
	public function remove() {

		$this->save(['status' => 30]);

		Db::name('ding_order_seat')->where('order_id', $this['id'])->update(['status' => 30]);

		// 删除分类记录
		return true;
	}

}
